import random
import re

from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from plone.app.layout.viewlets.common import ViewletBase

from zope.component import getMultiAdapter
from Products.CMFCore.utils import getToolByName
from zope.app.component.hooks import getSite



class menuTopView(ViewletBase):
    """
        Retorna los elementos del action menu_top
    """
    render = ViewPageTemplateFile('templates/menutop.pt')
    
    def update(self):
        context_state = getMultiAdapter((self.context,self.request),
                                            name=u'plone_context_state')
        actions = context_state.actions()
        self.menu = actions.get('menu_top',None)

class logoViewlet(ViewletBase):
    """logo viewlet"""
    render = ViewPageTemplateFile('templates/logo.pt')
    def update(self):
        super(logoViewlet, self).update()

        portal = self.portal_state.portal()
        logoName = portal.restrictedTraverse('base_properties').logoName
        self.logo_tag = portal.restrictedTraverse(logoName).tag()

        self.portal_title = self.portal_state.portal_title()
        miUtils = utils(self.context)
        catalog = miUtils.catalog
        portal = miUtils.portal
        portal = portal.getId()
        path = path = '/'+portal+'/logo'
        self.result = catalog.searchResults(path={'query':path,'depth':1},portal_type='Image',Title='logo.png')

class search(ViewletBase):
    """Viewlet search box """
    render = ViewPageTemplateFile('templates/search.pt')
    def update(self):
        super(search,self).update()

        context_state = getMultiAdapter((self.context, self.request),
                                            name=u'plone_context_state')
        props = getToolByName(self.context,'portal_properties')
        livesearch = props.site_properties.getProperty('enable_livesearch',False)
        if livesearch:
            self.search_input_id = "searchGadget"
        else:
            self.search_input_id = ""

        folder = context_state.folder()
        self.folder_path = '/'.join(folder.getPhysicalPath())

class entidadesView(ViewletBase):
    """
        Retorna las entidades del portal
    """
    
    render = ViewPageTemplateFile('templates/entidades.pt')

    def entidades(self):
        """retorna los usuarios pertenecientes al
        grupo entidades"""

        grouptool = getToolByName(self.context,'portal_groups')
        entidades = grouptool.getGroupById("Mis Entidades")

        miutils = utils(self.context)
        self.path = '/'+miutils.portal.getId()+'/Members'
        if entidades is None:
            return ()
        return entidades.getGroupMembers()


class multimediaView(ViewletBase):
    """
        Clase que obtiene las galerias de imagen y los videos
    """
    render = ViewPageTemplateFile('templates/multimedia.pt')
    
    def gallerys(self):
        """Retorna las galeria del portal"""
        miUtils = utils(self.context)
        catalog = miUtils.catalog
        portal = miUtils.portal
        portal = portal.getId()
        path = '/'+portal+'/galeria'
        result = catalog.searchResults(path={'query':path,'depth':1},portal_type='Gallery',
                                       sort_on='Date')
        return result
#        aleatorio = random.randint(1,len(result)-1)
#        objeto = result[aleatorio].getObject()
#        objetoUrl = objeto.absolute_url()
#        parent = re.match('http://.+/.+/galeria/(.+)/(.+)$', objetoUrl)
#        self.url = miUtils.portalUrl + '/galeria' + '/' + parent.group(1)
#        return result[aleatorio]

    def videos(self):
        """Retorna los videos del portal"""
        miUtils = utils(self.context)
        catalog = miUtils.catalog
        portal = miUtils.portal
        portal = portal.getId()
        path = '/'+portal+'/videos'
        result = catalog.searchResults(path={'query':path,'depth':1},portal_type=('RTInternalVideo','RTRemoteVideo'),
                                     sort_on='Date',sort_order='descending')
        return result

    def imgRemote(self,url):
        """Retorna la imagen thumb del
        video youtube"""

        videoId = re.match('http://www.youtube.com/watch\?v=(.{11})&?(.+)*',url)

        if videoId is not None:
            imageremote = 'http://img.youtube.com/vi/' + videoId.group(1)+ '/default.jpg'
        else:
            imageremote = ''

        return imageremote

class footerView(ViewletBase):
    render = ViewPageTemplateFile('templates/footer.pt')
    
    def footer(self):
        miutils = utils(self.context)
        return miutils.portalUrl


class colophonView(ViewletBase):
    render = ViewPageTemplateFile('templates/colophon.pt')

    def colophonContent(self):
        miUtils = utils(self.context)
        catalog = miUtils.catalog
        portal = miUtils.portal
        portal = portal.getId()
        pathSurvey = '/'+portal+'/encuestas'
        self.resultSurveys = catalog.searchResults(path={'query':pathSurvey,'depth':1},portal_type='PlonePopoll',sort_on='Date')

        pathBlog = '/'+portal
        self.resultBlogs = catalog.searchResults(path={'query':pathBlog},portal_type='BlogEntry',sort_on='Date')

        pathEvent = '/'+portal+'/eventos'
        self.resultEvents = catalog.searchResults(path={'query':pathEvent},portal_type='Event',sort_on='Date')

        return miUtils.portalUrl


class pathView(ViewletBase):
    render = ViewPageTemplateFile('templates/path.pt')
    
    def update(self):
        super(pathView,self).update()
        self.is_rtl = self.portal_state.is_rtl()
        breadcrumbs_view = getMultiAdapter((self.context,self.request),
                                            name=u'breadcrumbs_view')
        self.breadcrumbs = breadcrumbs_view.breadcrumbs()

        portal = getSite()
        self.portalUrl = portal.absolute_url()


class utils:
    """
    clase que contiene utiles como portal_catalog, portal root, etc
    """
    def __init__(self,context):
        self.context = context
        self.catalog = getToolByName(self.context,'portal_catalog')
        self.portal = getSite()
        self.portalUrl = self.portal.absolute_url()